const {User, Token} = require('../../mongodb/models')
const jwt = require('jsonwebtoken')
const config = require('../../config')
const {getUserByCtx} = require('../../utils/common')

module.exports = [
	{
		path: '/login',
		method: 'post',
		process: async (ctx, next) => {
			var userdata = await User.findOne({email:ctx.request.body.email, password:ctx.request.body.pwd})
			var user = {}
			// 授权token
			if(userdata){
				user = {
					_id: userdata._id,
					adminAuth: userdata.adminAuth,
					email: userdata.email
				}
				user.token = jwt.sign(user, config.secret, {expiresIn: config.tokenExpires})
				Token.create({
					userId: user._id,
					value: user.token,
					expire: ctx.request.body.expire
				})
			}
			ctx.response.body = {
				errCode: userdata ? 0 : 10001,
				errMsg: userdata ? 'request:success' : '用户名或密码错误',
				data: user
			}
		}
	},{
		path: '/logout',
		method: 'post',
		process: async (ctx, next) => {
			const {token} = getUserByCtx(ctx)
			const res = await Token.deleteMany({value: token})
			ctx.response.body = res.n ? {
				errCode: 0,
				errMsg: 'request:success'
			} : {
				errCode: -1,
				errMsg: token ? '退出失败' : '无效的token'
			}
		}
	}
]